package com.example.login.controller;
import com.example.login.entity.User;
import com.example.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping(value = "login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> checkLogin(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        User user = loginService.checkLogin(username,password);
        HashMap<String, Object> response = new HashMap<>();
        if (user != null) {
            response.put("code", 200);
            response.put("message", "登录成功");
            response.put("data", user);
            request.getSession().setAttribute("user", user);

        } else {
            response.put("code", 500);
            response.put("message", "用户名或密码错误");
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    public Map<String,Object>getAllLogin(){
        List<User>loginList = loginService.getAllLogin();
        HashMap reData = new HashMap();
        reData.put("data",loginList);
        return reData;
    }
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String, Object> register(@RequestParam("userName") String userName, @RequestParam("name") String name, @RequestParam("major") String major, @RequestParam("className") String className, @RequestParam("studentNum") String studentNum,@RequestParam("password")String password) {
        HashMap response = new HashMap();
        boolean isSuccess = loginService.register(userName, name, major, className, studentNum,password);
        if (isSuccess) {
            response.put("status", 200);
            response.put("message", "注册成功");
        } else {
            response.put("status", 400);
            response.put("message", "用户名或学号已存在");
        }
        return response;
    }
}
